package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB1EmailTemplates;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class LineTechCapacityValueServiceImpl implements LineTechCapacityValueService {

    @Autowired
    private LineTechCapacityValueDao lineTechCapacityValueDao;

    @Autowired
    private PcbaLineDao pcbaLineDao;

    @Autowired
    private TechCapacityRuleDao techCapacityRuleDao;

    @Autowired
    private BaseCapacityRuleDao baseCapacityRuleDao;

    @Autowired
    private LineTechBigTypeDao lineTechBigTypeDao;

    @Autowired
    private LineTechSmallTypeDao lineTechSmallTypeDao;

    @Autowired
    private CoreAlgorithmService coreAlgorithmService;

    @Autowired
    private PcbaDeviceRelatedTechParamDao pcbaDeviceRelatedTechParamDao;

    @Autowired
    private BisLineDao bisLineDao;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Autowired
    private PcbaWorkshopDao pcbaWorkshopDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ThirdApiService thirdApiService;

    @Autowired
    private AuditHistoryDao auditHistoryDao;

    @Autowired
    private BisDao bisDao;

    @Autowired
    private PcbaDeviceParamDao pcbaDeviceParamDao;

    @Autowired
    private PcbaDeviceRelatedDeviceParamDao pcbaDeviceRelatedDeviceParamDao;

    @Autowired
    private PcbaDeviceDao pcbaDeviceDao;

    @Autowired
    private PcbaDeviceResourceDao pcbaDeviceResourceDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private OperateService operateService;

    @Value("${personal.config.amazon-s3.url}")
    private String url;
    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;
    @Value("${personal.config.env}")
    private String env;

    @Value("${personal.config.sso.trusted-redirect-uri}")
    private String trustedRedirectUri;

    private String operateSmallType = "整线工艺能力";

    @Qualifier("MysqlTransactionManager1")
    @Autowired
    private DataSourceTransactionManager transactionManager1;

    @Override
    public Result getAllLineTechCapacityValueByLineId(Integer pcbaLineId) {
        try {
            if (pcbaLineId == null || "".equals(pcbaLineId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaLineId", "Miss Param pcbaLineId", null);
            }
            PcbaLine pcbaLine = pcbaLineDao.getPcbaLineById(pcbaLineId);
            if (pcbaLine == null) {
                return ResultUtil.error(500, "未找到pcbaLine", "Not Found pcbaLine", null);
            }
            Integer pcbaLineLevel = pcbaLine.getPcbaLineLevel();
            Integer lineTechBigTypeId = null;
            List<LineTechBigType> allLineTechBigType = lineTechBigTypeDao.getAllLineTechBigType("");
            for (LineTechBigType lineTechBigType : allLineTechBigType) {
                if (lineTechBigType.getLineLevelIds() != null && !"".equals(lineTechBigType.getLineLevelIds()) && pcbaLineLevel != null) {
                    if (lineTechBigType.getLineLevelIds().contains(pcbaLineLevel.toString())) {
                        lineTechBigTypeId = lineTechBigType.getLineTechBigTypeId();
                        break;
                    }
                }
            }

            Date d = new Date();
            /**
             * 对于新建的线体，由于 LineTechCapacityValue 表此时并没有数据，所以需要先新增
             */
            List<TechCapacityRule> techCapacityRuleList = techCapacityRuleDao.getAllTechCapacityRule(null, null, null);
            for (TechCapacityRule techCapacityRule : techCapacityRuleList) {
                String lineTechParamKey = techCapacityRule.getLineTechParamKey();
                String techCapacityRuleName = techCapacityRule.getTechCapacityRuleName();
                LineTechCapacityValue lineTechCapacityValueByKeyAndLineId = lineTechCapacityValueDao.getLineTechCapacityValueByKeyAndLineId(pcbaLineId, lineTechParamKey);
                if (lineTechCapacityValueByKeyAndLineId != null) {
                    // 什么都不用处理
                } else {
                    // insert
                    LineTechCapacityValue addLineTechCapacityValue = new LineTechCapacityValue();
                    addLineTechCapacityValue.setLineTechCapacityParamValue("");
                    addLineTechCapacityValue.setLineTechCapacityParamKey(lineTechParamKey);
                    addLineTechCapacityValue.setLineTechCapacityParamName(techCapacityRuleName);
                    addLineTechCapacityValue.setCreateTime(d);
                    addLineTechCapacityValue.setPcbaLineId(pcbaLineId);
                    addLineTechCapacityValue.setLineTechCapacityParamValueActual("");

                    lineTechCapacityValueDao.addLineTechCapacityValue(addLineTechCapacityValue);
                }
            }


            List<LineTechCapacityValue> allLineTechCapacityValueByLineId = lineTechCapacityValueDao.getAllLineTechCapacityValueByLineId(pcbaLineId);

            LineTechBigType lineTechBigType = null;
            if (lineTechBigTypeId != null) {
                lineTechBigType = lineTechBigTypeDao.getLineTechBigTypeById(lineTechBigTypeId);
                List<LineTechSmallType> list = lineTechSmallTypeDao.getAllLineTechSmallTypeByBigType("", lineTechBigTypeId);
                for (LineTechSmallType lineTechSmallType : list) {
                    List<TechCapacityRule> allTechCapacityRule = techCapacityRuleDao.getAllTechCapacityRule("", lineTechBigTypeId, lineTechSmallType.getLineTechSmallTypeId());
                    for (TechCapacityRule techCapacityRule : allTechCapacityRule) {

                        if("input_1691733815".equals(techCapacityRule.getLineTechParamKey())){
                            System.out.println("input_1691733815");
                        }
                        String ruleBaseCapacityParamKeys = techCapacityRule.getBaseCapacityParamKey();
                        BaseCapacityRule baseCapacityRuleByKey = baseCapacityRuleDao.getBaseCapacityRuleByKey(ruleBaseCapacityParamKeys);
                        techCapacityRule.setBaseCapacityRule(baseCapacityRuleByKey);
                        for (LineTechCapacityValue lineTechCapacityValue : allLineTechCapacityValueByLineId) {
                            if (lineTechCapacityValue.getLineTechCapacityParamKey().equals(techCapacityRule.getLineTechParamKey())) {
                                techCapacityRule.setActualValueAudit(lineTechCapacityValue.getLineTechCapacityParamValueActualAudit());
                                techCapacityRule.setDeclareValue(lineTechCapacityValue.getLineTechCapacityParamValue());
                                techCapacityRule.setCurrentFillValue(lineTechCapacityValue.getLineTechCapacityParamValueActual());

                                if(techCapacityRule.getTechCapacityRuleType() == 4){
                                    // 4：取多个设备基线能力的最大值
                                    double finalValue = -3.14159265371;

                                    // 根据 pcbaLineId 查询 线体下面的设备集合
                                    List<PcbaDevice> pcbaDeviceListByLine = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLineId);
                                    for (PcbaDevice pcbaDevice : pcbaDeviceListByLine) {
                                        Integer pcbaDeviceResourceId = pcbaDevice.getPcbaDeviceResourceId();

                                        String baseCapacityParamKey = techCapacityRule.getBaseCapacityParamKey();
                                        if(baseCapacityParamKey != null && !"".equals(baseCapacityParamKey)){
                                            String[] split = baseCapacityParamKey.split(",");
                                            for (String s : split) {
                                                try{
                                                    PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(s, pcbaDeviceResourceId);
                                                    String pcbaDeviceParamValue = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue();
                                                    if(CommonUtils.isNumeric(pcbaDeviceParamValue)){
                                                        if(finalValue < Double.parseDouble(pcbaDeviceParamValue) || finalValue == -3.14159265371){
                                                            finalValue = Double.parseDouble(pcbaDeviceParamValue);
                                                        }
                                                    }
                                                }catch (Exception e){

                                                }
                                            }
                                        }
                                        techCapacityRule.setDeclareValue(finalValue == -3.14159265371 ? "" : CommonUtils.formatDouble(finalValue));
                                    }
                                }
                                if(techCapacityRule.getTechCapacityRuleType() == 5){
                                    // 5：取多个设备基线能力的最小值[前两位]
                                    double finalValue = -3.14159265371;
                                    String finalValueStr = "";
                                    // 根据 pcbaLineId 查询 线体下面的设备集合
                                    List<PcbaDevice> pcbaDeviceListByLine = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLineId);
                                    for (PcbaDevice pcbaDevice : pcbaDeviceListByLine) {
                                        Integer pcbaDeviceResourceId = pcbaDevice.getPcbaDeviceResourceId();
                                        System.out.println(pcbaDeviceResourceId);
                                        String baseCapacityParamKey = techCapacityRule.getBaseCapacityParamKey();
                                        if(baseCapacityParamKey != null && !"".equals(baseCapacityParamKey)){
                                            String[] split = baseCapacityParamKey.split(",");
                                            for (String s : split) {
                                                if("input_1689737511515".equals(s)){
                                                    System.out.println(s);
                                                }
                                                try{
                                                    PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(s, pcbaDeviceResourceId);
                                                    String pcbaDeviceParamValue = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue();
                                                    if(CommonUtils.isNumeric(pcbaDeviceParamValue.substring(0, 2))){
                                                        if(finalValue > Double.parseDouble(pcbaDeviceParamValue.substring(0, 2)) || finalValue == -3.14159265371){
                                                            finalValue = Double.parseDouble(pcbaDeviceParamValue.substring(0, 2));
                                                            finalValueStr = pcbaDeviceParamValue;
                                                        }
                                                    }
                                                }catch (Exception e){

                                                }
                                            }
                                        }
                                        techCapacityRule.setDeclareValue(finalValue == -3.14159265371 ? "" : finalValueStr);
                                    }
                                }
                                if(techCapacityRule.getTechCapacityRuleType() == 6){
                                    // 6：取多个设备基线能力的最小值
                                    double finalValue = -3.14159265371;
                                    // 根据 pcbaLineId 查询 线体下面的设备集合
                                    List<PcbaDevice> pcbaDeviceListByLine = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLineId);
                                    for (PcbaDevice pcbaDevice : pcbaDeviceListByLine) {
                                        Integer pcbaDeviceResourceId = pcbaDevice.getPcbaDeviceResourceId();

                                        String baseCapacityParamKey = techCapacityRule.getBaseCapacityParamKey();
                                        if(baseCapacityParamKey != null && !"".equals(baseCapacityParamKey)){
                                            String[] split = baseCapacityParamKey.split(",");
                                            for (String s : split) {
                                                try{
                                                    PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(s, pcbaDeviceResourceId);
                                                    String pcbaDeviceParamValue = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue();
                                                    if(CommonUtils.isNumeric(pcbaDeviceParamValue)){
                                                        if(finalValue > Double.parseDouble(pcbaDeviceParamValue) || finalValue == -3.14159265371){
                                                            finalValue = Double.parseDouble(pcbaDeviceParamValue);
                                                        }
                                                    }
                                                }catch (Exception e){

                                                }
                                            }
                                        }
                                        techCapacityRule.setDeclareValue(finalValue == -3.14159265371 ? "" : CommonUtils.formatDouble(finalValue));
                                    }
                                }
                                if(techCapacityRule.getTechCapacityRuleType() == 7){
                                    // 7：取多个设备基线能力的最大值[前两位]
                                    double finalValue = -3.14159265371;
                                    String finalValueStr = "";
                                    // 根据 pcbaLineId 查询 线体下面的设备集合
                                    List<PcbaDevice> pcbaDeviceListByLine = pcbaDeviceDao.getPcbaDeviceByLine(pcbaLineId);
                                    for (PcbaDevice pcbaDevice : pcbaDeviceListByLine) {
                                        Integer pcbaDeviceResourceId = pcbaDevice.getPcbaDeviceResourceId();

                                        String baseCapacityParamKey = techCapacityRule.getBaseCapacityParamKey();
                                        if(baseCapacityParamKey != null && !"".equals(baseCapacityParamKey)){
                                            String[] split = baseCapacityParamKey.split(",");
                                            for (String s : split) {
                                                try{
                                                    PcbaDeviceRelatedDeviceParam pcbaDeviceRelatedDeviceParam = pcbaDeviceRelatedDeviceParamDao.getPcbaDeviceRelatedDeviceParamByKeyAndDeviceResourceId(s, pcbaDeviceResourceId);
                                                    String pcbaDeviceParamValue = pcbaDeviceRelatedDeviceParam.getPcbaDeviceParamValue();
                                                    if(CommonUtils.isNumeric(pcbaDeviceParamValue.substring(0, 2))){
                                                        if(finalValue <= Double.parseDouble(pcbaDeviceParamValue.substring(0, 2)) || finalValue == -3.14159265371){
                                                            finalValue = Double.parseDouble(pcbaDeviceParamValue.substring(0, 2));
                                                            finalValueStr = pcbaDeviceParamValue;
                                                        }
                                                    }
                                                }catch (Exception e){

                                                }
                                            }
                                        }
                                        techCapacityRule.setDeclareValue(finalValue == -3.14159265371 ? "" : finalValueStr);
                                    }
                                }

                                // 图片
                                String paramsPicture = techCapacityRule.getParamsPicture();
                                if(paramsPicture != null && !"".equals(paramsPicture)){
                                    if("h3c_pro".equals(env)){
                                        techCapacityRule.setParamsPictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(url + "/" + fileBucket + "/" + paramsPicture));
                                    }else{
                                        techCapacityRule.setParamsPictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(CommonUtils.returnHostPrefixUrl() + paramsPicture));
                                    }
                                }


                                if (techCapacityRule.getTechCapacityRuleType() == 3 && !"".equals(techCapacityRule.getBisKeys())) {
                                    // 值来自bis【优先数据库中的值】
                                    String bisKeys = techCapacityRule.getBisKeys();
                                    String[] split = bisKeys.split(",");
                                    Collections.reverse(Arrays.asList(split));
                                    for (String keyStr : split) {
                                        BisLine bisLine = bisLineDao.getBisLineByLineAndKey(pcbaLineId, keyStr);
                                        if (bisLine != null && bisLine.getIsOk() == 1) {
                                            String bisKey = bisLine.getBisKey();
                                            Bis bisByKey = bisDao.getBisByKey(bisKey);
                                            // 几个特殊的先写死
                                            if (bisByKey != null && bisByKey.getBisValue() != null && !"".equals(bisByKey.getBisValue())) {
                                                if ("input_1691733818".equals(lineTechCapacityValue.getLineTechCapacityParamKey()) || "input_1691733844".equals(lineTechCapacityValue.getLineTechCapacityParamKey())) {
                                                    // BGA最大长度（mm）
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue().split("×").length > 0 ? bisByKey.getBisValue().split("×")[0] : "");
                                                } else if ("input_1691733819".equals(lineTechCapacityValue.getLineTechCapacityParamKey()) || "input_1691733845".equals(lineTechCapacityValue.getLineTechCapacityParamKey())) {
                                                    // BGA最大宽度（mm）
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue().split("×").length > 1 ? bisByKey.getBisValue().split("×")[1] : "");
                                                } else if ("input_1691733820".equals(lineTechCapacityValue.getLineTechCapacityParamKey()) || "input_1691733846".equals(lineTechCapacityValue.getLineTechCapacityParamKey())) {
                                                    // 焊接型Socket最大长度（mm）
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue().split("×").length > 0 ? bisByKey.getBisValue().split("×")[0] : "");
                                                } else if ("input_1691733821".equals(lineTechCapacityValue.getLineTechCapacityParamKey()) || "input_1691733847".equals(lineTechCapacityValue.getLineTechCapacityParamKey())) {
                                                    // 焊接型Socket最大宽度（mm）
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue().split("×").length > 1 ? bisByKey.getBisValue().split("×")[1] : "");
                                                } else if ("input_1691733822".equals(lineTechCapacityValue.getLineTechCapacityParamKey()) || "input_1691733848".equals(lineTechCapacityValue.getLineTechCapacityParamKey())) {
                                                    // SMT DIMM最大长度（mm）
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue().split("×").length > 0 ? bisByKey.getBisValue().split("×")[0] : "");
                                                } else if ("input_1691733823".equals(lineTechCapacityValue.getLineTechCapacityParamKey()) || "input_1691733849".equals(lineTechCapacityValue.getLineTechCapacityParamKey())) {
                                                    // SMT DIMM最大宽度（mm）
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue().split("×").length > 1 ? bisByKey.getBisValue().split("×")[1] : "");
                                                } else if ("input_1691733824".equals(lineTechCapacityValue.getLineTechCapacityParamKey()) || "input_1691733850".equals(lineTechCapacityValue.getLineTechCapacityParamKey())) {
                                                    // SMT DIMM最大高度（mm）
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue().split("×").length > 2 ? bisByKey.getBisValue().split("×")[2] : "");
                                                } else {
                                                    techCapacityRule.setActualValue(bisByKey.getBisValue());
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    //System.out.println(techCapacityRule.getLineTechParamKey() + "-" + techCapacityRule.getActualValue());
                                    if (techCapacityRule.getActualValue() == null || "".equals(techCapacityRule.getActualValue())) {
                                        techCapacityRule.setActualValue(lineTechCapacityValue.getLineTechCapacityParamValueActual());
                                    }
                                } else {
                                    // 直接获取
                                    techCapacityRule.setActualValue(lineTechCapacityValue.getLineTechCapacityParamValueActual());
                                }
                                break;
                            }
                        }
                    }
                    lineTechSmallType.setTechCapacityRuleList(allTechCapacityRule);
                }
                lineTechBigType.setLineTechSmallTypeList(list);
            }

            return ResultUtil.success(lineTechBigType);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //@Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result updateLineTechCapacityValueDeclareByLineId(String data) {

        try {
            String userId = UserHeaderHolder.getUserId();
            Date d = new Date();
            JSONObject jsonObject = JSONObject.parseObject(data);
            String pcbaLineId = jsonObject.getString("pcbaLineId");
            /*String beginTimeStr = jsonObject.getString("beginTimeStr");
            String endTimeStr = jsonObject.getString("endTimeStr");*/
            String paramsStatus = jsonObject.getString("paramsStatus");
            if (pcbaLineId == null || "".equals(pcbaLineId)) {
                return ResultUtil.error(500, "缺少参数pcbaLineId", "Miss Param pcbaLineId", null);
            }
            /*if(beginTimeStr == null || "".equals(beginTimeStr)){
                return ResultUtil.error(500, "缺少参数beginTimeStr", "Miss Param beginTimeStr", null);
            }
            if(endTimeStr == null || "".equals(endTimeStr)){
                return ResultUtil.error(500, "缺少参数endTimeStr", "Miss Param endTimeStr", null);
            }*/
            if (paramsStatus == null || "".equals(paramsStatus)) {
                return ResultUtil.error(500, "缺少参数paramsStatus", "Miss Param paramsStatus", null);
            }

           /* SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date beginTime = format.parse(beginTimeStr);
            Date endTime = format.parse(endTimeStr);*/

            PcbaLine oldPcbaLine = pcbaLineDao.getPcbaLineById(Integer.parseInt(pcbaLineId));

            // 查询原有的宣称能力值
            List<LineTechCapacityValue> oldLineTechCapacityValueList = lineTechCapacityValueDao.getAllLineTechCapacityValueByLineId(Integer.parseInt(pcbaLineId));

            JSONArray lineTechCapacityValueList = jsonObject.getJSONArray("lineTechCapacityValueList");

            // 判断原先的有没有，有的话更新，没有的话插入
            for (Object o : lineTechCapacityValueList) {
                JSONObject jo = (JSONObject) o;
                String lineTechCapacityParamKey = jo.getString("lineTechCapacityParamKey");
                String lineTechCapacityParamName = jo.getString("lineTechCapacityParamName");
                String lineTechCapacityParamValue = jo.getString("lineTechCapacityParamValue");
                TechCapacityRule techCapacityRuleByKey = techCapacityRuleDao.getTechCapacityRuleByKey(lineTechCapacityParamKey);
                LineTechCapacityValue lineTechCapacityValueByKeyAndLineId = lineTechCapacityValueDao.getLineTechCapacityValueByKeyAndLineId(Integer.parseInt(pcbaLineId), lineTechCapacityParamKey);
                if (lineTechCapacityValueByKeyAndLineId != null) {
                    LineTechCapacityValue updateLineTechCapacityValue = new LineTechCapacityValue();
                    updateLineTechCapacityValue.setLineTechCapacityParamValue(lineTechCapacityParamValue);
                    updateLineTechCapacityValue.setLineTechCapacityParamKey(lineTechCapacityParamKey);
                    updateLineTechCapacityValue.setLineTechCapacityParamName(lineTechCapacityParamName);
                    updateLineTechCapacityValue.setCreateTime(d);
                    updateLineTechCapacityValue.setLineTechCapacityValueId(lineTechCapacityValueByKeyAndLineId.getLineTechCapacityValueId());
                    if (techCapacityRuleByKey != null && techCapacityRuleByKey.getActualEqualDeclare() != null && techCapacityRuleByKey.getActualEqualDeclare() == 1) {
                        updateLineTechCapacityValue.setLineTechCapacityParamValueActual(lineTechCapacityParamValue);
                    }
                    //update

                    lineTechCapacityValueDao.updateLineTechCapacityValue(updateLineTechCapacityValue);

                    // 操作记录
                    //operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(lineTechCapacityValueByKeyAndLineId), JSONObject.toJSONString(updateLineTechCapacityValue)));
                } else {
                    // insert
                    LineTechCapacityValue addLineTechCapacityValue = new LineTechCapacityValue();
                    addLineTechCapacityValue.setLineTechCapacityParamValue(lineTechCapacityParamValue);
                    addLineTechCapacityValue.setLineTechCapacityParamKey(lineTechCapacityParamKey);
                    addLineTechCapacityValue.setLineTechCapacityParamName(lineTechCapacityParamName);
                    addLineTechCapacityValue.setCreateTime(d);
                    addLineTechCapacityValue.setPcbaLineId(Integer.parseInt(pcbaLineId));
                    if (techCapacityRuleByKey != null && techCapacityRuleByKey.getActualEqualDeclare() != null && techCapacityRuleByKey.getActualEqualDeclare() == 1) {
                        addLineTechCapacityValue.setLineTechCapacityParamValueActual(lineTechCapacityParamValue);
                    }

                    lineTechCapacityValueDao.addLineTechCapacityValue(addLineTechCapacityValue);

                    // 操作记录
                    //operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(addLineTechCapacityValue)));
                }
            }

            // 将 pcba_line  is_filled_declare 改为1  lock_declare = 1
            PcbaLine updatePcbaLine = new PcbaLine();
            updatePcbaLine.setIsFilledDeclare(1);
            updatePcbaLine.setLockDeclare(1);
            updatePcbaLine.setPcbaLineId(Integer.parseInt(pcbaLineId));
            updatePcbaLine.setParamsStatusDeclare(Integer.parseInt(paramsStatus));
            updatePcbaLine.setBeginTimeDeclare(null);
            updatePcbaLine.setEndTimeDeclare(null);
            Integer integer = pcbaLineDao.updatePcbaLine(updatePcbaLine);
            //System.out.println("updatePcbaLine=" + integer);
            //System.out.println("updatePcbaLine.getLockDeclare()=" + updatePcbaLine.getLockDeclare());

          /* <p>1、如果与实际能力关联的宣称能力发生变动，则触发以下联动，否则无需联动</p>
          <div>&nbsp;&nbsp;&nbsp;1）联动修改线体的实际工艺能力值，修改线体的实际工艺能力认证状态修改为`待提交审核`【功能已完成】</div>*/

            // 判断原有的值 和新值是否有变化
            List<JSONObject> changeList = new ArrayList<>();
            for (Object o : lineTechCapacityValueList) {
                JSONObject jo = (JSONObject) o;
                String lineTechCapacityParamKey1 = jo.getString("lineTechCapacityParamKey");
                String lineTechCapacityParamValue1 = jo.getString("lineTechCapacityParamValue");

                TechCapacityRule techCapacityRule = techCapacityRuleDao.getTechCapacityRuleByKey(lineTechCapacityParamKey1);

                for (LineTechCapacityValue lineTechCapacityValue : oldLineTechCapacityValueList) {
                    String lineTechCapacityParamKey2 = lineTechCapacityValue.getLineTechCapacityParamKey();
                    String lineTechCapacityParamValue2 = lineTechCapacityValue.getLineTechCapacityParamValue();
                    Integer lineTechCapacityValueId2 = lineTechCapacityValue.getLineTechCapacityValueId();

                    if (lineTechCapacityParamKey1.equals(lineTechCapacityParamKey2)) {
                        JSONObject j = new JSONObject();
                        j.put("label", techCapacityRule != null ? techCapacityRule.getTechCapacityRuleName() : "");
                        j.put("key", lineTechCapacityParamKey1);
                        j.put("oldValue", lineTechCapacityParamValue2);
                        j.put("newValue", lineTechCapacityParamValue1);
                        j.put("actualEqualDeclare", techCapacityRule != null ? techCapacityRule.getActualEqualDeclare() : "");
                        j.put("lineTechCapacityValueId", lineTechCapacityValueId2);
                        changeList.add(j);
                        break;
                    }
                }
            }
            if (changeList.size() > 0) {
                for (JSONObject object : changeList) {
                    String actualEqualDeclare = object.getString("actualEqualDeclare");
                    String lineTechCapacityParamKey = object.getString("key");
                    String newValue = object.getString("newValue");
                    String oldValue = object.getString("oldValue");
                    String lineTechCapacityParamName = object.getString("label");
                    String lineTechCapacityValueId = object.getString("lineTechCapacityValueId");

                    LineTechCapacityValue lineTechCapacityValue = new LineTechCapacityValue();
                    lineTechCapacityValue.setUpdateTime(new Date());
                    lineTechCapacityValue.setPcbaLineId(Integer.parseInt(pcbaLineId));
                    lineTechCapacityValue.setLineTechCapacityParamValueActual(newValue);
                    lineTechCapacityValue.setLineTechCapacityParamKey(lineTechCapacityParamKey);
                    lineTechCapacityValue.setLineTechCapacityParamName(lineTechCapacityParamName);
                    lineTechCapacityValue.setLineTechCapacityValueId(Integer.parseInt(lineTechCapacityValueId));
                    /*if(oldPcbaLine.getParamsStatusActual() != null && oldPcbaLine.getParamsStatusActual() == 1){
                        // 原先状态为认证通过的才 记录原先值
                        lineTechCapacityValue.setLineTechCapacityParamValueActualAudit(oldValue);
                    }
                    lineTechCapacityValueDao.updateLineTechCapacityValue(lineTechCapacityValue);
                    //if("1".equals(actualEqualDeclare)){
                    if(!oldValue.equals(newValue)){
                        pcbaLineDao.auditPcbaLineParamTechActual(Integer.parseInt(pcbaLineId), 4, "");
                    }
                    //}*/
                    if ("1".equals(actualEqualDeclare)) {
                        lineTechCapacityValueDao.updateLineTechCapacityValue(lineTechCapacityValue);
                        if (!oldValue.equals(newValue)) {
                            pcbaLineDao.auditPcbaLineParamTechActual(Integer.parseInt(pcbaLineId), 4, "");
                        }
                    }

                }
            }

            // 级联触发 线体的最终状态
            coreAlgorithmService.cascadeUpdateLineFinalStatus(3, null, null, Integer.parseInt(pcbaLineId));

            // 操作记录
            operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaLine), JSONObject.toJSONString(updatePcbaLine)));

            return ResultUtil.success(null);
        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //@Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result updateLineTechCapacityValueActualByLineId(String data) {
        Integer pLineId = null;
        String userId = UserHeaderHolder.getUserId();
        Date d = new Date();
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String pcbaLineId = jsonObject.getString("pcbaLineId");
            String beginTimeStr = jsonObject.getString("beginTimeStr");
            String endTimeStr = jsonObject.getString("endTimeStr");
            String paramsStatus = jsonObject.getString("paramsStatus");
            if (pcbaLineId == null || "".equals(pcbaLineId)) {
                return ResultUtil.error(500, "缺少参数pcbaLineId", "Miss Param pcbaLineId", null);
            }
            if (beginTimeStr == null || "".equals(beginTimeStr)) {
                return ResultUtil.error(500, "缺少参数beginTimeStr", "Miss Param beginTimeStr", null);
            }
            if (endTimeStr == null || "".equals(endTimeStr)) {
                return ResultUtil.error(500, "缺少参数endTimeStr", "Miss Param endTimeStr", null);
            }
            if (paramsStatus == null || "".equals(paramsStatus)) {
                return ResultUtil.error(500, "缺少参数paramsStatus", "Miss Param paramsStatus", null);
            }


            pLineId = Integer.parseInt(pcbaLineId);
            PcbaLine oldPcbaLine = pcbaLineDao.getPcbaLineById(Integer.parseInt(pcbaLineId));

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date beginTime = format.parse(beginTimeStr);
            Date endTime = format.parse(endTimeStr);

            JSONArray lineTechCapacityValueList = jsonObject.getJSONArray("lineTechCapacityValueList");

            // 插入新的
            for (Object o : lineTechCapacityValueList) {
                JSONObject jo = (JSONObject) o;
                String lineTechCapacityParamKey = jo.getString("lineTechCapacityParamKey");
                String lineTechCapacityParamName = jo.getString("lineTechCapacityParamName");
                String lineTechCapacityParamValue = jo.getString("lineTechCapacityParamValue");

                LineTechCapacityValue oldLineTechCapacityValue = lineTechCapacityValueDao.getLineTechCapacityValueByKeyAndLineId(pLineId, lineTechCapacityParamKey);


                if (oldLineTechCapacityValue != null) {
                    LineTechCapacityValue updateLineTechCapacityValue = new LineTechCapacityValue();
                    //updateLineTechCapacityValue.setLineTechCapacityParamValueActualAudit(oldLineTechCapacityValue.getLineTechCapacityParamValueActual());
                    updateLineTechCapacityValue.setLineTechCapacityParamValueActual(lineTechCapacityParamValue);
                    updateLineTechCapacityValue.setUpdateTime(d);
                    updateLineTechCapacityValue.setLineTechCapacityValueId(oldLineTechCapacityValue.getLineTechCapacityValueId());
                    lineTechCapacityValueDao.updateLineTechCapacityValue(updateLineTechCapacityValue);

                    // 操作记录
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldLineTechCapacityValue), JSONObject.toJSONString(updateLineTechCapacityValue)));
                }
            }

            // 将 pcba_line  is_filled_actual 改为1 ,params_status 4 ,认证开始和结束时间
            PcbaLine updatePcbaLine = new PcbaLine();
            updatePcbaLine.setIsFilledActual(1);
            updatePcbaLine.setParamsStatusActual(Integer.parseInt(paramsStatus));
            updatePcbaLine.setBeginTimeActual(beginTime);
            updatePcbaLine.setEndTimeActual(endTime);
            updatePcbaLine.setPcbaLineId(Integer.parseInt(pcbaLineId));
            updatePcbaLine.setSubmitter(Integer.parseInt(userId));
            pcbaLineDao.updatePcbaLine(updatePcbaLine);

            /*if("3".equals(paramsStatus)){
                // 添加 审核记录
                AuditHistory addAuditHistory = new AuditHistory();
                addAuditHistory.setAuditType(3);
                addAuditHistory.setCreateTime(d);
                addAuditHistory.setSubmitUserId(Integer.parseInt(userId));
                addAuditHistory.setAuditUserId(null);
                addAuditHistory.setAuditStatus(Integer.parseInt(paramsStatus));
                addAuditHistory.setAuditNotes(null);
                addAuditHistory.setRelatedId(Integer.parseInt(pcbaLineId));
                auditHistoryDao.addAuditHistory(addAuditHistory);
            }*/

            // 级联触发 线体的最终状态
            coreAlgorithmService.cascadeUpdateLineFinalStatus(3, null, null, Integer.parseInt(pcbaLineId));

            if (Integer.parseInt(paramsStatus) == 3) {
                //发送邮件
                try {
                    String companyName = "";
                    String workshopName = "";
                    String lineName = "";
                    List<User> userList = new ArrayList<>();
                    PcbaLine pcbaLine = pcbaLineDao.getPcbaLineById(Integer.parseInt(pcbaLineId));
                    if (pcbaLine != null) {
                        PcbaCompany pcbaCompany = pcbaCompanyDao.getPcbaCompanyById(pcbaLine.getPcbaCompanyId());
                        PcbaWorkshop pcbaWorkshop = pcbaWorkshopDao.getPcbaWorkshopById(pcbaLine.getPcbaWorkshopId());
                        if(pcbaWorkshop != null){
                            workshopName = pcbaWorkshop.getPcbaWorkshopNameCn();
                        }
                        lineName = pcbaLine.getPcbaLineNameCn();
                        if (pcbaCompany != null) {
                            companyName = pcbaCompany.getPcbaCompanyNameCn();
                            String emailOwners5 = pcbaCompany.getEmailOwners5();
                            if (emailOwners5 != null && !"".equals(emailOwners5)) {
                                String[] split = emailOwners5.split(",");
                                for (String s : split) {
                                    if (s.contains("/")) {
                                        String[] strings = s.split("\\/");
                                        if (strings.length == 2) {
                                            String domainAccount = strings[1];
                                            if (domainAccount != null && !"".equals(domainAccount)) {
                                                User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                                if (u != null) {
                                                    userList.add(u);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    List<MailAddress> mailAddressList = new ArrayList<>();
                    for (User user : userList) {
                        if(user.getEmail().contains(",")){
                            String[] emailsArr = user.getEmail().split(",");
                            for (String email : emailsArr) {
                                MailAddress mailAddress = new MailAddress();
                                mailAddress.setMailAddress(email);
                                mailAddress.setType(0);
                                mailAddressList.add(mailAddress);
                            }
                        }else{
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(user.getEmail());
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }

                    String mailContent = "<html><body>" +
                            "<p>主题：" + DB1EmailTemplates.LINE_TECH_PARAMS_TITLE + "</p>" +
                            "<p>相关线体：" + companyName + "/" + workshopName + "/" + lineName + "</p>" +
                            "<p>网页链接：" + "<a href='" + trustedRedirectUri + DB1EmailTemplates.LINE_TECH_PARAMS_WEB_URL + "'>点击跳转</a>" +  "</p>" +
                            "</html></body>";

                    if (mailAddressList.size() > 0) {
                        Result result = thirdApiService.sendMail("", DB1EmailTemplates.LINE_TECH_PARAMS_TITLE, DB1EmailTemplates.LINE_TECH_PARAMS_MAIL_CONTENT_TITLE,
                                mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
                        if (result.getCode() == 200) {
                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                            System.out.println("整线实际工艺能力,发送成功");
                        } else {
                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                            System.out.println("整线实际工艺能力,发送失败:" + result.getMsgCn());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                    System.out.println("整线实际工艺能力：" + e.getMessage());
                }
            }

            // 操作记录
            operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaLine), JSONObject.toJSONString(updatePcbaLine)));

            return ResultUtil.success(null);
        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
